package com.dongdongshop.callback;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.pojo.order_item.TbOrderItem;
import com.dongdongshop.service.item.ItemService;
import com.dongdongshop.service.item_jpa.ItemJpaService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;

import java.util.List;

@RocketMQTransactionListener(txProducerGroup = "tx-group")
public class TxMessageCallBack implements RocketMQLocalTransactionListener {
    @Reference
    private ItemService itemService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Reference
    private ItemJpaService itemJpaService;
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            List<TbOrderItem> orderItemList = (List<TbOrderItem>) o;
            /*itemService.updateToNum(orderItemList);*/
            itemJpaService.updateToNum(orderItemList);
        }catch (Exception e){
            redisTemplate.opsForValue().set(message.getHeaders().get("TRANSACTION_ID"),"2");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        redisTemplate.opsForValue().set(message.getHeaders().get("TRANSACTION_ID"), "1");
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //通过事务id获取 redis中 对应的本地事务执行状态
        String status = (String) redisTemplate.opsForValue().
                get(message.getHeaders().get("TRANSACTION_ID").toString());
        if ("1".equals(status)) {
            return RocketMQLocalTransactionState.COMMIT;
        } else if ("2".equals(status)) {
            //继续处理，或者直接回滚
            return RocketMQLocalTransactionState.ROLLBACK;
        } else {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
